package com.homework.controller;

import com.homework.dto.AdminLoginDTO;
import com.homework.dto.Result;
import com.homework.entity.Admin;
import com.homework.mapper.AdminMapper;
import com.homework.service.AuthService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {

    private final AuthService authService;

    @Autowired
    private AdminMapper adminMapper;

    /**
     * 管理员登录
     */
    @PostMapping("/login")
    public Result<String> login(@Valid @RequestBody AdminLoginDTO loginDTO, HttpSession session) {
        log.info("收到登录请求 - 用户名: {}, IP: {}",
                loginDTO.getUsername(),
                session.getAttribute("ip") != null ? session.getAttribute("ip") : "unknown");

        Result<String> result = authService.login(loginDTO, session);
        log.info("登录处理结果: {}", result.getMessage());

        return result;
    }

    /**
     * 管理员登出
     */
    @PostMapping("/logout")
    public Result<String> logout(HttpSession session) {
        return authService.logout(session);
    }

    /**
     * 检查登录状态
     */
    @GetMapping("/status")
    public Result<Boolean> checkLoginStatus(HttpSession session) {
        return authService.checkLoginStatus(session);
    }

    /**
     * 调试接口：检查admin用户是否存在
     */
    @GetMapping("/check-admin")
    public Result<String> checkAdminUser() {
        try {
            log.info("检查admin用户是否存在");
            Admin admin = adminMapper.selectOne(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<Admin>()
                    .eq(Admin::getUsername, "admin")
            );

            if (admin == null) {
                log.warn("admin用户不存在");
                return Result.error("admin用户不存在");
            }

            log.info("admin用户存在 - ID: {}, 用户名: {}, 创建时间: {}",
                    admin.getId(), admin.getUsername(), admin.getCreatedAt());

            return Result.success("admin用户存在，ID: " + admin.getId() + ", 创建时间: " + admin.getCreatedAt());

        } catch (Exception e) {
            log.error("检查admin用户时发生错误", e);
            return Result.error("检查失败: " + e.getMessage());
        }
    }

    /**
     * 调试接口：获取所有admin用户（不包含密码）
     */
    @GetMapping("/list-admins")
    public Result<List<Admin>> listAdmins() {
        try {
            log.info("获取所有admin用户列表");
            List<Admin> admins = adminMapper.selectList(null);

            // 隐藏密码信息
            admins.forEach(admin -> {
                admin.setPassword("***HIDDEN***");
                admin.setSalt("***HIDDEN***");
            });

            log.info("找到{}个admin用户", admins.size());
            return Result.success(admins);

        } catch (Exception e) {
            log.error("获取admin用户列表时发生错误", e);
            return Result.error("获取失败: " + e.getMessage());
        }
    }
}